-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathKahn's Algorithm.cpp
More file actions
60 lines (53 loc) · 897 Bytes
/
Kahn's Algorithm.cpp
File metadata and controls
60 lines (53 loc) · 897 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*input
5 5
1 3
2 3
3 4
3 5
5 4
*/
/* Topological Sorting in a Direct Acyclic Graph
Time Complexity: O(V+E)
*/
#include <iostream>
#include <vector>
#include <queue>
const int N = 100001;
std::vector < int > v[N];
int indegree[N];
void kahn(int n)
{
std::queue < int > q;
for(int i = 1; i <= n; i ++) {
if(indegree[i] == 0) {
q.push(i);
}
}
while(!q.empty()) {
int d = q.front();
q.pop();
std::cout << d << " ";
for(auto x: v[d]) {
indegree[x] --;
if(indegree[x] == 0) {
q.push(x);
}
}
}
}
int main ()
{
int n, m;
std::cin >> n >> m;
for(int i = 0; i < m; i ++) {
int x, y;
std::cin >> x >> y;
v[x].push_back(y);
indegree[y] ++;
}
kahn(n);
return 0;
}
/* Expected Output
1 2 3 5 4
*/